{extend name="layout/iframe_layout" /}

{block name="title"}修改数据表{/block}
{block name="style"}
<style>
.crud-generator {
  padding: 20px;
}

.columns-config {
  margin: 20px 0;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.draggable-column {
  cursor: move;
  padding: 10px;
  margin-bottom: 5px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.draggable-column:hover {
  background-color: #e9eef5;
}

.draggable-column .el-form-item {
  margin-bottom: 10px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.drag-handle {
  cursor: move;
  color: #909399;
}

.delete-column {
  cursor: pointer;
  color: #f56c6c;
}

.table-config {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.deleted-column {
  background-color: #fef0f0;
  opacity: 0.8;
}

.table-search {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>
{/block}

{block name="content"}

<div id="app" >
    <div class="crud-generator">
      <!-- 表搜索 -->
      <div class="table-search">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form :inline="true" :model="searchForm">
              <el-form-item label="表名">
                <el-input
                  v-model="searchForm.tableName"
                  placeholder="请输入表名包含前缀，如:bs_order"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getTableInfo" :loading="isLoading">查询</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      
      <!-- 表结构编辑 -->
      <el-form :model="config" label-width="150px" v-if="tableLoaded">
        <!-- 表配置 -->
        <div class="table-config">
          <el-row :gutter="20">
            <el-col :span="12">
              <!-- 表名输入 -->
              <el-form-item label="表名" required>
                <el-input
                  v-model="config.tableName"
                  placeholder="请输入表名包含前缀，如:bs_order"
                  style="width: 300px"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 表注释 -->
              <el-form-item label="表注释">
                <el-input
                  v-model="config.tableComment"
                  placeholder="请输入表注释"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <!-- 字符集选择 -->
              <el-form-item label="字符集">
                <el-select v-model="config.charset" placeholder="请选择字符集" style="width: 300px;">
                  <el-option label="utf8mb4" value="utf8mb4"></el-option>
                  <el-option label="utf8" value="utf8"></el-option>
                  <el-option label="gbk" value="gbk"></el-option>
                  <el-option label="latin1" value="latin1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 排序规则 -->
              <el-form-item label="排序规则">
                <el-select v-model="config.collation" placeholder="请选择排序规则" style="width: 300px;">
                  <el-option label="utf8mb4_unicode_ci" value="utf8mb4_unicode_ci"></el-option>
                  <el-option label="utf8mb4_general_ci" value="utf8mb4_general_ci"></el-option>
                  <el-option label="utf8_unicode_ci" value="utf8_unicode_ci"></el-option>
                  <el-option label="utf8_general_ci" value="utf8_general_ci"></el-option>
                  <el-option label="gbk_chinese_ci" value="gbk_chinese_ci"></el-option>
                  <el-option label="gbk_bin" value="gbk_bin"></el-option>
                  <el-option label="latin1_swedish_ci" value="latin1_swedish_ci"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 字段配置 -->
        <div class="columns-config">
          <el-button type="primary" @click="addColumn" size="small" icon="el-icon-plus">添加字段</el-button>
          
          <draggable v-model="columns" tag="div" handle=".drag-handle">
            <div v-for="(column, index) in columns" :key="index" class="draggable-column" :class="{'deleted-column': column.markAsDeleted}">
              <div class="column-header">
                <i class="el-icon-rank drag-handle"></i>
                <i class="el-icon-delete delete-column" @click="toggleDeleteColumn(index)"></i>
              </div>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="字段名" required>
                    <el-input v-model="column.field" placeholder="字段名" :disabled="column.markAsDeleted"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="类型" required>
                    <el-select v-model="column.type" placeholder="请选择类型" style="width: 100%;" @change="onTypeChange(column)" :disabled="column.markAsDeleted">
                      <el-option label="INT" value="INT"></el-option>
                      <el-option label="VARCHAR" value="VARCHAR"></el-option>
                      <el-option label="TEXT" value="TEXT"></el-option>
                      <el-option label="DATE" value="DATE"></el-option>
                      <el-option label="DATETIME" value="DATETIME"></el-option>
                      <el-option label="TINYINT" value="TINYINT"></el-option>
                      <el-option label="SMALLINT" value="SMALLINT"></el-option>
                      <el-option label="MEDIUMINT" value="MEDIUMINT"></el-option>
                      <el-option label="BIGINT" value="BIGINT"></el-option>
                      <el-option label="FLOAT" value="FLOAT"></el-option>
                      <el-option label="DOUBLE" value="DOUBLE"></el-option>
                      <el-option label="DECIMAL" value="DECIMAL"></el-option>
                      <el-option label="CHAR" value="CHAR"></el-option>
                      <el-option label="TINYTEXT" value="TINYTEXT"></el-option>
                      <el-option label="MEDIUMTEXT" value="MEDIUMTEXT"></el-option>
                      <el-option label="LONGTEXT" value="LONGTEXT"></el-option>
                      <el-option label="TIME" value="TIME"></el-option>
                      <el-option label="TIMESTAMP" value="TIMESTAMP"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="长度">
                    <el-input v-model="column.length" placeholder="长度" :disabled="column.markAsDeleted"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="小数点">
                    <el-input v-model="column.decimal" placeholder="小数点" :disabled="column.markAsDeleted"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="是否NULL">
                    <el-select v-model="column.nullable" placeholder="是否NULL" style="width: 100%;" :disabled="column.markAsDeleted">
                      <el-option label="NULL" value="NULL"></el-option>
                      <el-option label="NOT NULL" value="NOT NULL"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="键">
                    <el-select v-model="column.key" placeholder="键类型" style="width: 100%;" :disabled="column.markAsDeleted">
                      <el-option label="无" value=""></el-option>
                      <el-option label="PRIMARY KEY" value="PRIMARY KEY"></el-option>
                      <el-option label="UNIQUE" value="UNIQUE"></el-option>
                      <el-option label="INDEX" value="INDEX"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="无符号(数值)">
                    <el-select v-model="column.unsigned" placeholder="是否无符号" style="width: 100%;" :disabled="!isNumericType(column.type) || column.markAsDeleted">
                      <el-option label="否" value=""></el-option>
                      <el-option label="是" value="UNSIGNED"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="自增">
                    <el-select v-model="column.autoIncrement" placeholder="是否自增" style="width: 100%;" :disabled="column.key !== 'PRIMARY KEY' || column.markAsDeleted">
                      <el-option label="否" value=""></el-option>
                      <el-option label="是" value="AUTO_INCREMENT"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="注释">
                    <el-input v-model="column.comment" placeholder="注释" :disabled="column.markAsDeleted"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="默认值">
                    <el-input v-model="column.default" placeholder="默认值" :disabled="column.markAsDeleted"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </draggable>
        </div>

        <!-- 生成按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleGenerate" :loading="isGenerating">保存修改</el-button>
        </el-form-item>
      </el-form>
    </div>
</div>
{/block}

{block name="script"}
<script src="/static/lib/sortablejs/Sortable.min.js"></script>
<script src="/static/lib/vuedraggable/vuedraggable.umd.min.js"></script>
<script>
  var api_base = '/curd';
  new Vue({
    el: '#app',
    components: {
      draggable: window.vuedraggable
    },
    data() {
      return {
        searchForm: {
          tableName: ''
        },
        config: {
          tableName: '',
          tableComment: '',
          charset: 'utf8mb4',
          collation: 'utf8mb4_unicode_ci'
        },
        originalColumns: [],
        columns: [],
        isLoading: false,
        isGenerating: false,
        tableLoaded: false
      };
    },
    methods: {
      addColumn() {
        this.columns.push({
          field: '',
          type: 'VARCHAR',
          length: '255',
          decimal: '',
          nullable: 'NULL',
          key: '',
          comment: '',
          default: '',
          unsigned: '',
          autoIncrement: '',
          markAsDeleted: false
        });
      },
      toggleDeleteColumn(index) {
        // 标记为删除而不是立即删除，这样可以撤销操作
        this.columns[index].markAsDeleted = !this.columns[index].markAsDeleted;
      },
      isNumericType(type) {
        const numericTypes = ['INT', 'TINYINT', 'SMALLINT', 'MEDIUMINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'DECIMAL'];
        return numericTypes.includes(type);
      },
      onTypeChange(column) {
        // 如果类型改变了，重置无符号和自增选项
        column.unsigned = '';
        column.autoIncrement = '';
        
        // 根据类型设置默认长度
        switch(column.type) {
          case 'VARCHAR':
            column.length = '255';
            break;
          case 'CHAR':
            column.length = '10';
            break;
          case 'INT':
            column.length = '';
            break;
          case 'TINYINT':
            column.length = '';
            break;
          case 'SMALLINT':
            column.length = '';
            break;
          case 'MEDIUMINT':
            column.length = '';
            break;
          case 'BIGINT':
            column.length = '';
            break;
          case 'FLOAT':
            column.length = '';
            break;
          case 'DOUBLE':
            column.length = '';
            break;
          case 'DECIMAL':
            column.length = '10';
            column.decimal = '2';
            break;
          default:
            column.length = '';
            column.decimal = '';
        }
      },
      // 获取表信息
      async getTableInfo() {
        if (!this.searchForm.tableName) {
          this.$message.error('请输入表名');
          return;
        }
        
        this.isLoading = true;
        this.tableLoaded = false;
        
        try {
          const res = await post(api_base+'/table_info', {table_name: this.searchForm.tableName});
          if (res.code === 0) {
            const data = res.data;
            this.config.tableName = data.table_name;
            this.config.tableComment = data.table_comment;
            this.config.charset = data.charset;
            this.config.collation = data.collation;
            
            // 处理字段信息
            this.columns = data.columns.map(column => ({
              ...column,
              markAsDeleted: false
            }));
            
            // 保存原始字段信息，用于比较
            this.originalColumns = JSON.parse(JSON.stringify(this.columns));
            
            this.tableLoaded = true;
          } else {
            this.$message.error(res.msg);
          }
        } catch (error) {
          console.error('获取表信息失败:', error);
          this.$message.error('获取表信息失败，请检查网络或联系管理员');
        } finally {
          this.isLoading = false;
        }
      },
      // 保存表修改
      async handleGenerate() {
        if (!this.config.tableName) {
          this.$message.error('表名不能为空');
          return;
        }
        
        if (this.columns.length === 0) {
          this.$message.error('请至少保留一个字段');
          return;
        }
        
        this.isGenerating = true;
        try {
          // 分离需要删除的字段和需要修改/新增的字段
          const deletedColumns = this.columns.filter(column => column.markAsDeleted);
          const activeColumns = this.columns.filter(column => !column.markAsDeleted);
          
          const config = {
            tableName: this.config.tableName,
            tableComment: this.config.tableComment,
            charset: this.config.charset,
            collation: this.config.collation,
            columns: activeColumns,
            deletedColumns: deletedColumns
          };
          
          const res = await post(api_base+'/edit_table_save', config);
          if (res.code === 0) {
            this.$message.success('修改成功');
          } else {
            this.$message.error(res.msg);
          }
        } catch (error) {
          console.error('修改失败:', error);
          this.$message.error('操作失败，请检查网络或联系管理员');
        } finally {
          this.isGenerating = false;
        }
      }
    },
    mounted() {
      // 页面加载时不自动查询表信息
    }
  });
</script>
{/block}
